/* QtLua -- Lua bindings for Qt
   Copyright (C) 2011, Jarek Pelczar

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General
   Public License along with this library; if not, write to the
   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301 USA

*/

#include "wrap_convertableobject_p.h"
#include "qluaengineglobals_p.h"
#include <QDebug>

namespace QLuaInternal {

int ConvertableObject::obj_New(lua_State * L)
{
    QLuaScriptEngine * engine = QLuaEngineGlobals::engineFromLua(L);
    Q_ASSERT_X(engine != NULL, "ConvertableObject::obj_New", "Called from incorrect context");
    QLuaScriptEnginePrivate * priv = QLuaScriptEnginePrivate::priv(engine);

    int meta_type_id = lua_tointeger(L, lua_upvalueindex(1));

    QLuaMetaTypeRegistryEntry * metaEntry = priv->m_metaRegistry.value(meta_type_id, NULL);
    Q_ASSERT_X(metaEntry != NULL, "ConvertableObject::obj_New", "Trying to allocate object of invalid metatype");

    QLuaScriptValue result(metaEntry->m_toScriptFunc(engine, NULL));

    result.setRawProperty("__qtlua_internal_meta_type_id", QLuaScriptValue(meta_type_id));

    if(metaEntry->m_prototype.isTable() || metaEntry->m_prototype.isUserData())
    {
        result.setMetaTable(metaEntry->m_prototype);
    }

    result.pushToStack(engine);

    return 1;
}

}
